<template>
  <div class="page-module">
    <div
      class="page-module-item"
      v-for="(item, index) in list"
      :key="item.id"
      draggable="true"
      @dragstart="drag($event, index)"
      @drop="drop($event, index)"
      @dragover="allowDrop($event)"
    >
      <div class="page-module-item-icon">
        <menu-outlined />
      </div>
      <div class="page-module-item-list">
        <div class="page-module-item-list-info">
          <div class="page-module-item-list-info-left">
            <div class="page-module-item-list-info-left-icon w-[37.6px] h-[39.85px]">
              <a-image
                width="37.6px"
                height="39.85px"
                :src="getIcon(item)"
                class="w-[-webkit-fill-available] object-contain"
                :fallback="defaultImage"
              />
            </div>
            <div class="page-module-item-list-info-left-content">
              <div class="title">{{ item.name }}</div>
              <div class="arguments">
                <span
                  >广告库ID:{{ item.id }}
                  <copy-outlined class="text-[#0083ff] ml-[8px]" @click="() => copy(item.id)" />
                </span>
                <span>创建人：{{ item.create_user }}</span>
                <span>创建时间：{{ formatToDateTime(+item.create_at * 1000) }}</span>
              </div>
            </div>
          </div>
          <div class="page-module-item-list-info-right">
            <span class="common-btn width-88" @click="handleManage(item)">管理内容</span>
            <span class="common-btn width-58" @click="updateAd(item.id)">编辑</span>
            <span
              class="common-btn width-58"
              :class="item.status === 1 ? 'common-del' : 'common-active'"
              @click="deleteAd(item.id)"
              >删除</span
            >
          </div>
        </div>
        <div class="page-module-item-list-total">
          <div class="page-module-item-list-total-type">
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">启动广告:</span>
              <span class="item-num">{{ formatNumber(item.start_adv) }}</span>
            </div>
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">弹窗广告:</span>
              <span class="item-num">{{ formatNumber(item.pop_adv) }}</span>
            </div>
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">轮播广告:</span>
              <span class="item-num">{{ formatNumber(item.carousel_adv) }}</span>
            </div>
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">横幅广告:</span>
              <span class="item-num">{{ formatNumber(item.banner_adv) }}</span>
            </div>
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">底部浮层广告:</span>
              <span class="item-num">{{ formatNumber(item.bottom_adv) }}</span>
            </div>
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">播放前广告:</span>
              <span class="item-num">{{ formatNumber(item.before_play_adv) }}</span>
            </div>
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">播放暂停广告:</span>
              <span class="item-num">{{ formatNumber(item.suspend_play_adv) }}</span>
            </div>
            <div class="page-module-item-list-total-type-item">
              <span class="item-text">专栏广告:</span>
              <span class="item-num">{{ formatNumber(item.column_adv) }}</span>
            </div>
          </div>
          <div class="page-module-item-list-total-switch">
            <a-switch
              v-model:checked="item.status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) =>handleSwitch(checked,item)"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- 禁用对话框 -->
  <modal-view
    title="提示"
    v-model:visible="disabledVisible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="disableConfirm"
    @cancel="disableCancel"
  >
    <span>{{ type === 1 ? disabledText : activeText }}</span>
  </modal-view>
  <!-- 删除对话框 -->
  <modal-view
    title="提示"
    v-model:visible="deleteVisible"
    okText="确定"
    cancelText="取消"
    :width="458"
    @confirm="deleteConfirm"
    @cancel="deleteCancel"
  >
    <span>{{ deleteText }}</span>
  </modal-view>
</template>
<script lang="ts" setup>
import type { AdItem } from '@/types/advertising/advertising'

import { computed, ref, toRefs, inject, nextTick } from 'vue'
import useStore from '@/stores'
import router from '@/router'
import { formatNumber, formatToDateTime } from '@/utils/format'
import ModalView from '@/components/components/modal/ModalView.vue'
import useClipboard from 'vue-clipboard3'
import { message } from 'ant-design-vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
import defaultImage from '@/assets/icon/defaultImage.png'
const {
  advertising: { delete_library, update_status_library, library_order }
} = apis
const { toClipboard } = useClipboard()
const { permission } = useStore()
interface SiteData {
  type: number | undefined
  list: AdItem[]
}
//props
const props = defineProps<SiteData>()
const { list, type } = toRefs(props)
console.log('list: ', list)
//emit
const emit = defineEmits(['update-list'])
//删除相关数据
const deleteId = ref<string>('')
const deleteVisible = ref(false)
//禁用相关数据
const checkedValue = ref(1)
const checkedId = ref('')
const disabledVisible = ref(false)
const baseUrl: any = inject('baseUrl')
// console.log('import.meta.env.VITE_BASE_URL: ', import.meta.env.VITE_BASE_URL)
//弹框展示文本
const activeText = ref('启用广告会获取该广告的应用内容，确定要启用该广告吗？')
const disabledText = ref('禁用广告库可能导致使用该广告库的应用停止广告展示，确定要禁用吗？')
const deleteText = ref('删除广告库不可恢复，可能导致使用该广告库的应用广告为空，确定要删除吗？')
// const clickVal = ref<AdItem>()
// const moveVal = ref<AdItem>()
// const endVal = ref<AdItem>()
// 复制广告库ID
// const dragstart = (item: AdItem): void => {
//   clickVal.value = item
//   console.log('clickVal.value: ', clickVal.value)
// }
// const dragenter = (item: AdItem): void => {
//   moveVal.value = item
//   console.log('moveVal.value: ', moveVal.value)
// }
// const dragend = (item: AdItem): void => {
//   endVal.value = item
//   let index = list.value.indexOf(item) //移动元素的当前位置
//   let moveObj = moveVal.value ? moveVal.value : ''
//   let addIndex = list.value.indexOf(moveObj as AdItem) //要移动后的位置
//   list.value.splice(index, 1)
//   list.value.splice(addIndex, 0, item)
// }
const drag = (event: any, index: number) => {
  event.dataTransfer.setData('index', index)
}
//排序方法
const orderFunc = (currentIndex: number) => {
  const { id, order } = list.value[currentIndex]
  const params = {
    id,
    order
  }
  library_order(params).then(() => {
    message.success('排序成功')
  })
}
const drop = (event: any, index: number) => {
  event.preventDefault()
  let startIndex = +event.dataTransfer.getData('index')
  let currentIndex: number = +index
  console.log('start', startIndex)
  console.log('drop', currentIndex)

  if (startIndex - currentIndex > 0) {
    console.log('要拖拽的元素的索引 大于 当前位置的元素的索引')
    list.value[startIndex].order = list.value[currentIndex].order
    list.value.splice(currentIndex, 0, list.value[startIndex])
    console.log('删除' + (startIndex + 1))
    list.value.splice(startIndex + 1, 1)
    orderFunc(currentIndex)
  } else if (startIndex - currentIndex < 0) {
    console.log('要拖拽的元素的索引  小于 当前位置的元素的索引')
    list.value.splice(currentIndex + 1, 0, list.value[startIndex])
    list.value.splice(startIndex, 1)
    orderFunc(currentIndex)
  } else {
    console.log('什么也不用做')
  }
  console.log('list.value: ', list.value)
  // list.value.forEach((item, index) => {
  //   item.site_order = (index + 1).toString()
  // })
  console.log(list.value[currentIndex], 'list.value[currentIndex]')
}
const allowDrop = (event: any) => {
  event.preventDefault()
}
const copy = async (id: string) => {
  try {
    await toClipboard(id)
    message.success('复制成功')
  } catch (e) {
    console.error(e)
  }
}
//根据类型获取图片
const getIcon = computed(() => (item: AdItem) => {
  if (item.icon_type === 1) return baseUrl + item.icon_url
  return item.icon_url
})
//内容管理
const handleManage = (item: AdItem) => {
  nextTick(() => {
    console.log('item: ', item.name)
    permission.setSiteName(item.name)
    router.push({ name: 'StartAd' })
    storage.set('libraryId', item.id)
    permission.setSiderType('AD_BANK')
  })
}
//新建广告库
const updateAd = (id: string) => {
  router.push({ name: 'EditAd', query: { id: id } })
}
//删除广告库
const deleteAd = (id: string) => {
  if (type.value === 1) {
    return message.warning('启用中广告不能删除！')
  } else {
    deleteId.value = id
    console.log('deleteId.value: ', deleteId.value, id)
    deleteVisible.value = true
  }
}
//禁用相关事件
const handleSwitch = (checked: number, item: any) => {
  console.log(checked, item, 'item')
  if (type.value === 1) {
    disabledVisible.value = true
    checkedValue.value = checked
    checkedId.value = item.id
  } else {
    const data = {
      status: checked,
      id: item.id
    }
    update_status_library(data).then(() => {
      message.success('启用成功')
      disabledVisible.value = false
      emit('update-list')
    })
  }
}
//禁用确认
const disableConfirm = (value: any) => {
  console.log('value: ', value)
  const data = {
    status: checkedValue.value,
    id: checkedId.value
  }
  //请求
  update_status_library(data).then(() => {
    message.success('修改成功')
    emit('update-list')
    disabledVisible.value = false
  })
}
//禁用取消
const disableCancel = () => {
  disabledVisible.value = false
  emit('update-list')
}
//删除相关事件
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  delete_library({ id: deleteId.value }).then((res: any) => {
    message.success('删除成功')
    emit('update-list')
    deleteVisible.value = value
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
</script>

<style lang="less" scoped>
.common-btn {
  height: 32px;
  line-height: 18px;
  padding: 6px 14px;
  box-sizing: border-box;
  border: 1px solid #d9d9d9;
  margin-left: 16px;
  font-size: 14px;
  color: #262626;
  border-radius: 6px;
}

.common-active {
  color: #fe4c4d;
  background: rgba(254, 76, 77, 0.08);
  border: 1px solid rgba(254, 76, 77, 1);
}

.common-del {
  color: #f0aaaa;
  background: rgba(254, 76, 77, 0.08);
  border: 1px solid #f4c2bf;
}

.page-module-item:hover .page-module-item-icon {
  visibility: visible;
}

.page-module-item:hover {
  box-shadow: 1px 1px 10px 0px rgba(0, 0, 0, 0.15);
}

.page-module {
  min-height: 240px;
  max-height: calc(100vh - 239px);
}
.page-module-item {
  width: 100%;
  min-height: 144px;
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  border: 1px solid rgba(217, 217, 217, 1);

  border-radius: 6px;
  cursor: pointer;

  &-icon {
    width: 40px;
    text-align: center;
    visibility: hidden;
  }

  &-list {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding-right: 32px;
    box-sizing: border-box;

    &-info {
      min-height: 89px;
      padding: 24px 0 24px 2px;
      box-sizing: border-box;
      border-bottom: 1px solid #f4f4f4;
      display: flex;
      flex-wrap: wrap;

      &-left {
        width: 50%;
        display: flex;

        &-icon {
          width: 37.6px;
          height: 39.85px;
          margin-right: 16px;

          img {
            width: 100%;
            height: 100%;
          }
        }

        &-content {
          flex: 1;

          .title {
            font-size: 14px;
            color: #262626;
            font-weight: 500;
          }

          .arguments {
            font-size: 12px;
            color: #bfbfbf;
            white-space: nowrap;
            display: flex;
            flex-wrap: wrap;

            span {
              margin-right: 24px;
            }

            a {
              cursor: pointer;
            }
          }
        }
      }

      &-right {
        width: 50%;
        display: flex;
        justify-content: flex-end;
        .width-88 {
          min-width: 88px;
        }
        .width-58 {
          min-width: 58px;
        }
      }
    }

    &-total {
      min-height: 54px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      &-type {
        width: 95%;
        display: flex;
        flex-wrap: wrap;

        &-item {
          display: flex;
          align-items: flex-start;
          flex-wrap: nowrap;
          margin-right: 41px;
          margin: 5px 20px 5px 0;

          .item-img {
            width: 15px;
            height: 15px;
            line-height: 18px;

            img {
              width: 100%;
            }
          }

          .item-text {
            font-size: 14px;
            color: #595959;
            margin: 0 9px;
            white-space: nowrap;
          }

          .item-num {
            font-size: 14px;
            font-weight: 500;
          }
        }
      }

      &-switch {
        width: 5%;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
</style>
